import logging

import uvicorn
from sqlalchemy.orm import Session

from SecurityConfig import auth_middleware, process_time_middleware, log_requests, signature_verification_middleware
from models.sysModel.mylab import AmSysUser
from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from LoggingConfig import setup_logging
from datebase import engine, Base, get_db
from routers import include_route
from utils.EncryptionUtil import TokenVerify, EncryptionMiddleware

app = FastAPI(openapi_tags=[
    {
        "name": "实验室管理系统",
        # "description": "登录/注册/权限管理",
        # "externalDocs": {
        #     "description": "详细说明文档",
        #     "url": "https://example.com/docs/auth"
        # }
    }
])

# 跨域设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# app.middleware("http")(auth_middleware)
# app.middleware("http")(signature_verification_middleware)
app.middleware("http")(process_time_middleware)
app.middleware("http")(log_requests)

# 日志设置
setup_logging()
logger = logging.getLogger(__name__)

# 注册路由
include_route(app)

# 创建数据库表
Base.metadata.create_all(bind=engine)


# 路由
@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.post("/token")
def login(login_form: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = db.query(AmSysUser).filter(AmSysUser.id == login_form.username).filter(
        AmSysUser.password_clear == login_form.password).first()
    tokenVerify = TokenVerify(user_name=user.username, user_id=user.id)
    token = EncryptionMiddleware.encrypt_token(tokenVerify)
    prefix = "Bearer "
    return prefix + token


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
